//
//  DataBaseSimple.m
//  侧滑Demo
//
//  Created by 毛志 on 14-7-2.
//  Copyright (c) 2014年 maozhi. All rights reserved.
//

#import "DataBaseSimple.h"
#import "FMDatabase.h"

@implementation DataBaseSimple
{
    FMDatabase * _dataBase;
}

-(id) initWithDB:(NSString *)fileName {
    self = [super init];
    if (self) {
        NSString * MessagePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
        DLog(@"FMDB Path :%@",MessagePath);
        _dataBase = [FMDatabase databaseWithPath:MessagePath];
        if (![_dataBase open]) {
            return nil;
        }
        [self createTable];
    }
    return self;
}

-(void) close {
    [_dataBase close];
}

-(void)createTable{
    if (![_dataBase executeUpdate:@"create table if not exists Message (id integer primary key autoincrement, MsgData blob,Seq integer,RecieveTime text,unique(Seq) on conflict replace)"]) {
        return;
    }
}

-(void)dropTable{
    [_dataBase executeUpdate:@"drop table if exists Message"];
}


- (void)insertDBwithFuseMsgArray:(NSArray *)array useTransaction:(BOOL)useTransaction
{
    [_dataBase open];
    if (useTransaction) {
        [_dataBase beginTransaction];
        BOOL isRollBack = NO;
        @try {
            
                for (int i = 0; i<array.count; i++) {
                    FuseMsg *fuse = (FuseMsg *)array[i] ;

                    NSArray * params = [NSArray arrayWithObjects:fuse.msg.data,[[NSNumber alloc] initWithLong:fuse.msg.msgHead.msgSeq],fuse.recieveTimeStamp ,nil];
                    if (![_dataBase executeUpdate:@"insert into Message (MsgData,Seq,RecieveTime) values (?,?,?)" withArgumentsInArray:params]) {
                        DLog(@"insertDBwithmsgError");
                        return;
                    }

                }
        }
        @catch (NSException *exception) {
            isRollBack = YES;
            [_dataBase rollback];
        }
        @finally {
            if (!isRollBack) {
                [_dataBase commit];
            }
        }
        
    }
    else
    {

            
            for (int i = 0; i<array.count; i++) {
                FuseMsg *fuse = (FuseMsg *)array[i] ;
                NSArray * params = [NSArray arrayWithObjects:fuse.msg.data,[[NSNumber alloc] initWithLong:fuse.msg.msgHead.msgSeq],fuse.recieveTimeStamp ,nil];
                if (![_dataBase executeUpdate:@"insert into Message (MsgData,Seq,RecieveTime) values (?,?,?)" withArgumentsInArray:params]) {
                    DLog(@"insertDBwithmsgError");
                    return;
                }
            }

    }

}


- (void)deleteDBwithKey:(UInt64)seq
{
    if (![_dataBase executeUpdate:@"delete from Message where Seq=?",[[NSNumber alloc] initWithLong:seq]]) {
        DLog(@"deleteDBwithmsgError");
        return;
    }
}

- (void)updateDBwithKey:(UInt64)seq withmsg:(FuseMsg *)fuseMsg
{
    if (![_dataBase executeUpdate:@"update Message set MsgData=?,RecieveTime=? where Seq = ?",fuseMsg.msg.data,[[NSNumber alloc] initWithLong:seq]]) {

        return;
    }
}

- (FuseMsg *)selectDBwithKey:(UInt64)seq
{
    FuseMsg *fuseMsg = [[FuseMsg alloc]init];
    
    FMResultSet * set = [_dataBase executeQuery:@"select * from Message where Seq=?",[[NSNumber alloc] initWithLong:seq]];
        while ([set next]) {
            
           fuseMsg.msg =[Msg parseFromData:[set dataForColumn:@"MsgData"]] ;
            
        }
        
    
    return fuseMsg;
}

- (NSArray *)selectAll
{
    NSMutableArray *array = [[NSMutableArray alloc]init];

    FMResultSet * set = [_dataBase executeQuery:@"select * from Message Order By RecieveTime desc,Seq desc limit 100"];
    while ([set next]) {
        FuseMsg *fuseMsg = [[FuseMsg alloc]init];
        
        fuseMsg.msg =[Msg parseFromData:[set dataForColumn:@"MsgData"]] ;
        fuseMsg.recieveTimeStamp =[set stringForColumn:@"RecieveTime"]; ;
        
        [array addObject:fuseMsg];
        
    }
        
    return array;
        
}

@end
